const SESSION_KEY = "sessions"

/**
 * 这里面的数据实际是保存到数据库中的，现在的Demo阶段是把数据存储到了localStorage中
 *
 * @author Junpeng.Li
 * @date 2022-4-6 22:55:52
 */

export function add(data) {
    return new Promise(resolve => {
        const sessions = findAll()

        data.id = new Date().getTime()
        sessions[data.id] = data

        localStorage.setItem(SESSION_KEY, JSON.stringify(sessions))

        resolve()
    })
}

export function edit(data) {
    return new Promise(resolve => {
        const sessions = findAll()
        sessions[data.id] = data

        localStorage.setItem(SESSION_KEY, JSON.stringify(sessions))

        resolve()
    })
}

export function findAll() {
    const sessions = localStorage.getItem(SESSION_KEY)
    if (!sessions) {
        return {}
    }

    return JSON.parse(sessions)
}

export function getOne(id) {
    return findAll()[id]
}

export function removeById(id) {
    return new Promise(resolve => {
        const sessions = findAll()
        delete sessions[id]

        localStorage.setItem(SESSION_KEY, JSON.stringify(sessions))

        resolve()
    })
}